package com.ruoyi.tzzl.api;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.AlipayOpenOperationOpenbizmockOpenidtestingQueryModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.tzzl.domain.WzPayOrderRecord;
import com.ruoyi.tzzl.service.IWzPayOrderRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * @author by caoyong
 * @date 2022/12/6
 **/
@Slf4j
public class PayApi {


    //应用AppId
    private static final String appId = "2021003167623438";
    //PKCS8格式的应用私钥
    private static final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQgh61ooeh2sIaz4oKKyvL4XuHIfQdy79833ntL10NyJDSKeNBVzyU0Bjo0o80Pjtj1gxYMp5JvncZQkHJORLcOsqKugp9GG1w/wBaJp7ESXlFRn2eRjbe+JRmirMW5QEOn88XX/+9WCKEpstCzN7sIH+MErujbzOfrLsLU0SMAQvgW/1g3UESOws9f07KL0xDpCI//utWP4yk+34l60rFDbo5+3LQE0ikFI7IyeS2QuuGKo3E4LhEHp+80UI8Ml7uv/qB7QyG2dfUIkNRvcQqwf4+WtYX//SbxsVOv6uxj3wkBa95FZQs9kHKzBfm/P3S6kzEpYlw6lg63ik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HrLWPAO3tAP+frd7Ss4+UioevA191MUqWOrbtJZ5dpm3R72Mi6hply61GHxr0B30PJpDVkPl2xy2o1HNYtdiDSB6maHvE3Fk3Gp59qpHubhU4Cgy8UeN8Ms2qVdIka8Dj6RIv30znsJ8X28vUySnU";
    //应用公钥证书文件路径
    private static final String CertPath = "E:\\weizan\\tzzl\\tzzl-doc\\zfb\\crt\\appCertPublicKey_2021003167623438.crt";
    //支付宝公钥证书文件路径
    private static final String alipayPublicCertPath = "E:\\weizan\\tzzl\\tzzl-doc\\zfb\\crt\\alipayCertPublicKey_RSA2.crt";
    //支付宝根证书文件路径
    private static final String RootCertPath = "E:\\weizan\\tzzl\\tzzl-doc\\zfb\\crt\\alipayRootCert.crt";

    private static final String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAh5rIKqVYnZ1aSWkb4FhFTOjlx2ntiaHdQFbNwHaeFPXWielPBjIDsu4yQ+6YWbcAvTex+aC/Qf01gue+1MKizE+gQkKH7EkjkXSYHFsFl3TiMk6OIcBstqqf+YNUQa5F/iedXxnu4XP/a0Bqfe/jr+rC1oWc0NsY9xEwm5AUyJHDTRo0FKO8u/hGbFZYqLtTgUXGvRHX3ExAKh7fMB6Uul2CBwkiTD+nOUJHeprv2PJtHNRRIO6yDHI9ZRqIOtIW8RYxSkBa8Tb/u35p6PRl7D+lkI4sDBobNaWtD0jJRk23GXOtnyDnIwWN4fjECzv61BA5Bufey1bZU899fskIYwIDAQAB";

/**
 * 统一下单接口（支付宝）
 * 1.【授权】       调用支付宝官方授权接口进行授权user_id
 * 2. 【预下单】    调用统一下单接口上送user_id获取prepay_id
 * 3.【拉起支付】 调用支付宝官方接口拉起支付
 * */


    /**
     * 微信授权
     */
    public static String authorization() {
     String appid ="wx9d39c57043608c87";
     String redirect_uri = "https://tzz.funongkj.com/prod-api/callback/weChatAuthorization"; //回调地址

      String url ="https://open.weix.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

     String ret = HttpUtils.sendGet(url);



        return null;
    }


    /**
     * 支付宝转账
     * identity 支付宝账号  name 实名姓名   amount 转账金额
     */
    public static JSONObject pay(String identity , String name , String amount) throws AlipayApiException {
        CertAlipayRequest certParams = new CertAlipayRequest();
        certParams.setServerUrl("https://openapi.alipay.com/gateway.do");
        //请更换为您的AppId
        certParams.setAppId("2021003167623438");
        //请更换为您的PKCS8格式的应用私钥
        certParams.setPrivateKey("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCLzXjJLqHVeSUNrloMpU1FRq65C/Go+UZW50w43F3tB1PPvtgxnc6BURE03wMqJhbPMNsj/xMArW/G2ZXc9S541mb89hv/7gjpu69t8dOSqGCTAeuVJNS+j7G3aWfTJhxD9Nm/axkRTlzewFiJpAEd/YmBMp/ZAzEiu12jDpgDAIwG9JCAorJjGgim0Nhl2v41tD6FcWhwM/kKhje+1O78Ovn8fsEHeOIRSGAZk347G2mKctDDnatFYCbuQUBv6qRLGCv1Qcuu6Qwk1bKMKzyVGdDVH7+QPfbMvLBzcc2DUY6qFApRwFrh74EthEOuEneiRI6vW7E2/fL1UyAzpj1jAgMBAAECggEAPbwCNnTNKgNRBXWUdjkYohrQVQ6dLEzHbuC8m+9T2rN9oyNXPLG+2wP9YSeJsjcXo26jloWw0n/D+D9lGil62Al1eQcE3kMy1GP418gN8ZlA7CnQ6g9VksDJbYCyRF9z495fuVOFwkqkYAj4D+/IPoITEmZUh/QM4pVyh+qN3eTcis6jI+Dg0GQJhZLOQIoo35nyWrJAAASlBfbwGtkDHoxFZFdBnJYxT4qVQXV+yDQD+3Br62tby/WvWab+w3TkFzbFgoWosu7JC8Fw2lKRe/69bQtIaAdGOsKnJItzR1Lx+pjHBadAdZCm6hYj3S3d0cDPZtULkrosZmXLYwgIIQKBgQDJNhH6A4/3meEI5TUrC2HYyxY6LmkDjUNnl8lcwuXYnoOStgJI+xnyGYpGDGWerhBCXqu0/xw1czPNwfek+VJ8B/vvMdekK2Puxx0sxzuA4R7KI8ioXRIGMYTMD+p4USiHsvRwvkMAMQoP180Y+ddovXCHU3I3djBozwEU0NqtZwKBgQCx3sNBlMeszF1AEb+8Cxqx6LMEec85zfyo/ZVHPfMjmnmx7eFLd2hnRAfMdHmOeOK1PaSUbUqodfxo45/VVD1wFv9Ad5hWNv1rQhmA43E0DiLI4SwoVOUeDmJM2R7h0i4ugq/qQ7cL0FeoFZdW+ZEwy29aMfFzdPXidkSVO6F2pQKBgElnvXUteYdGDy/0lsoGVAMITCqbpdoS3iVb3a1GuR2m7q9GUV0YpmWJZcWaXjReojXkXdYhP8RMK/kDq3n3L11qeEHSOC5/WezRnVYptQ6WkmoCVgD+O0YhKKZdpBeS3CttYPoEn2LhgR84hm13MFvYyMXF7qRHLO//nRBgBXc/AoGAR4Mlg796jDnaIAFC0iqwv+ir2NfUfgwYUiUqGGuKzryzwtq+IuZOPn52mDgYCzUFCRNQkTBjvNk68zzZLR7iWKeWVmf/AmK3fqEjudM311L7n0IQy+Jd/7iOwxDkPqyPTrnSWmCBPqm0JGsR3rEWM8UG7v93cREMLtGX/1vrLdUCgYBHadI8d3KWeqp8QLH/sXpCfkL09rOSDRbWBpxDBhE//U4OpE/DAaj23KVM+fy1ASx+7uV4TNtOZ28pMj+odRDGQu6cOKUDlACdAGpcISyG/fFMZrqsgV4j/cdVdv4KWrQ1VVpRBptTgxNF3xw4v64u+TXWRWw77cj5DeIjaSVYIg==");
        //请更换为您使用的字符集编码，推荐采用utf-8
        certParams.setCharset("utf-8");
        certParams.setFormat("json");
        certParams.setSignType("RSA2");
        //请更换为您的应用公钥证书文件路径
        certParams.setCertPath("E:\\weizan\\tzzl\\tzzl-doc\\zfb\\证书\\证书20221214112646\\appCertPublicKey_2021003167623438.crt");
        //请更换您的支付宝公钥证书文件路径
        certParams.setAlipayPublicCertPath("E:\\weizan\\tzzl\\tzzl-doc\\zfb\\证书\\证书20221214112646\\alipayCertPublicKey_RSA2.crt");
        //更换为支付宝根证书文件路径
        certParams.setRootCertPath("E:\\weizan\\tzzl\\tzzl-doc\\zfb\\证书\\证书20221214112646\\alipayRootCert.crt");
        AlipayClient alipayClient = new DefaultAlipayClient(certParams);
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
        model.setOutBizNo(IdUtils.get16UUID("TX")); //商户端的唯一订单号，对于同一笔转账请求，商户需保证该订单号唯一。
        model.setRemark("天作之恋提现打款下发"); //	业务备注
        model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}"); //是否展示付款方别名
        model.setBizScene("DIRECT_TRANSFER"); //业务场景，单笔无密转账固定为DIRECT_TRANSFER
        Participant payeeInfo = new Participant();
        payeeInfo.setIdentity(identity); //参与方的标识ID，比如支付宝用户UID。(收款账号)
        payeeInfo.setIdentityType("ALIPAY_LOGON_ID"); //参与方的标识类型，目前支持如下枚举：1、ALIPAY_USER_ID 支付宝的会员ID 2、ALIPAY_LOGON_ID：支付宝登录号，支持邮箱和手机号格式
        payeeInfo.setName(name); //参与方真实姓名
        model.setPayeeInfo(payeeInfo);
        model.setTransAmount(amount); //订单总金额，单位为元，精确到小数点后两位
        model.setProductCode("TRANS_ACCOUNT_NO_PWD");  //销售产品码，单笔无密转账固定为TRANS_ACCOUNT_NO_PWD
        model.setOrderTitle("天作之恋提现打款下发"); //转账业务的标题，用于在支付宝用户的账单里显示。
        request.setBizModel(model);
        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());
        log.info("支付宝转账接口调用返回信息:{}", response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(response.getBody());
        System.out.println("返回信息:"+jsonObject);
        JSONObject jsonObject1 = jsonObject.getJSONObject("alipay_fund_trans_uni_transfer_response");
       return  jsonObject1;
    }

    /**
     * 定额支付
     */
    public static JSONObject fixedPayment(String money,Long wid) {
        //公共参数
        SortedMap<String, Object> parmasMap = new TreeMap<>();
        parmasMap.put("app_id", "202212070732366"); //商户开放平台id
        parmasMap.put("method", "fbpay.order.qrcode"); //接口名称
        parmasMap.put("nonce", IdUtils.get16UUID("")); //随机数
        //请求参数
        JSONObject jsonRequest = new JSONObject();
        jsonRequest.put("merchant_order_sn", IdUtils.get16UUID("ZF"));//外部系统订单号
        jsonRequest.put("merchant_id", "1978147"); //商户开放平台id
        jsonRequest.put("total_amount", money); //订单总金额
        jsonRequest.put("pay_type", "alipay"); //支付方式，alipay 支付宝
        jsonRequest.put("store_id", "1330671");//商户门店号
        jsonRequest.put("notify_url", "https://tzz.funongkj.com/prod-api/callback/pay");//第三方回调地址
        parmasMap.put("biz_content", jsonRequest.toString());
        //进行签名
        String sign = Encryption.sign(parmasMap, jsonRequest);
        parmasMap.put("sign", sign); //签名
        System.out.println("加密后:" + sign);
        System.out.println("请求集合:" + parmasMap.toString());
        JSONObject jsonObject = new JSONObject(parmasMap);
        String ret = HttpUtils.sendPost("https://shq-api.51fubei.com/gateway/agent", jsonObject.toString());
        System.out.println("请求报文:" + jsonObject.toString());
        System.out.println("接口返回:" + ret);
        return JSONObject.parseObject(ret).getJSONObject("data");
    }


    /**
     * 统一下单
     * */
    public static  String placeTheOrder(){
        return "";
    }

    //定额支付
    public static void main(String[] args) throws AlipayApiException {
//        fixedPayment("0.1");
    }


}


